﻿using UnityEngine;

public class BallSpawner : MonoBehaviour 
{	
	public GameObject ballPrefab;
	
	public float ballSpawnFreq = 4.0f;
		
	public float spawnDistance = 200.0f;
	
	private readonly static Vector3 ballPrefabRotation = new Vector3(90.0f, 0.0f, 0.0f);
	
	private float ballSpawnTime = 0.0f;
	
	private BallList ballList;
	
	private GameState gameState;
	
	void Start() 
	{
		ballList = (BallList) GetComponent("BallList");
		gameState = (GameState) GetComponent("GameState");
		
		//Ignore collisions on Ball layer
		Physics.IgnoreLayerCollision(8, 8, true);
	}
	
	void Update() 
	{	
		if (gameState.gameState == GameState.State.PLAY)
		{
			ballSpawnTime += Time.deltaTime;
			
			if (ballSpawnTime > ballSpawnFreq) 
			{
				ballSpawnTime = 0.0f;
				SpawnBall();
			}
		}
		else
		{
			ballSpawnTime = 0.0f;
		}
	}
	
	public void SpawnBall()
	{
		Quaternion rotation = Quaternion.identity;
		rotation.eulerAngles = ballPrefabRotation;
		
		Color col = gameState.gameData.GetNextBall();
		
		if (col != Color.clear)
		{
			ballList.CreateBall(ballPrefab, GenerateSpawnPoint(), rotation, col);
		}
	}
	
	Vector3 GenerateSpawnPoint() 
	{
		float angle = Random.value * Mathf.PI * 2.0f;
		
		// Generate spawn point on a circle around 0,0
		float posX = Mathf.Cos(angle) * spawnDistance;
		float posY = Mathf.Sin(angle) * spawnDistance;
				
		return new Vector3(posX, posY, 0.0f);
	}
}
